package net.jeebiz.cloud.extras.core;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import net.jeebiz.cloud.api.dao.entities.PairModel;
import net.jeebiz.cloud.extras.core.dao.IDictDao;

@Component
public class DictRedisTemplate {
	
	private static final String KEY_PREFIX = "Dict:";
	
	@Autowired
	private RedisTemplate<String, Object> redisTemplate;
	@Autowired
	private ListOperations<String, Object> listOperations;
	@Autowired
	private IDictDao dictDao;
	
	@SuppressWarnings("unchecked")
	public List<PairModel> get(String key){
		if(getRedisTemplate().hasKey(KEY_PREFIX + key)) {
			List<Object> list =  getListOperations().range(KEY_PREFIX + key,0,-1);
			return (List<PairModel>) list.get(0);
		} else {
			List<PairModel> retList = getDictDao().getPairValues(key);
			getListOperations().leftPush(KEY_PREFIX + key, retList);
			//getListOperations().leftPushAll(KEY_PREFIX + key, retList);
			return retList;
		}
	}
	
	public RedisTemplate<String, Object> getRedisTemplate() {
		return redisTemplate;
	}

	public ListOperations<String, Object> getListOperations() {
		return listOperations;
	}

	public IDictDao getDictDao() {
		return dictDao;
	}

}
